package com.shunhe.zs_pda.base

import android.util.Log
import com.google.gson.Gson
import com.ruitu.arad.api.okhttp.MyOkHttp
import com.ruitu.router_module.Config
import com.shunhe.zs_pda.model.User
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONArray
import org.json.JSONException
import java.util.concurrent.TimeUnit

class Gl {
    companion object {
        const val DATE_FORMATE_1 = "yyyy-MM-dd HH:mm:ss"
        var user: User.UserInfo? = null

        fun isAdmin(): Boolean {
            return null != user && user!!.group_id == "1"
        }

        @JvmField
        var okHttp: MyOkHttp? = null
        private var logInterceptor: HttpLoggingInterceptor? = null

        @JvmField
        var gson = Gson()

        @JvmStatic
        fun <T> getStringToBean(jsonStr: String?, rows: Class<T>?): T? {
            try {
                val gson = Gson()
                return gson.fromJson(jsonStr, rows)
            } catch (e: Exception) {
                Log.e("HTTPERROR", "Gl->>>数据解析异常" + e.message)
            }
            return null
        }

        @JvmStatic
        fun <T> getStringToBeanArray(jsonStr: String?, rows: Class<T>?): ArrayList<T>? {
            try {
                val gson = Gson()
                try {
                    val jsonArray = JSONArray(jsonStr)
                    val mlist = ArrayList<T>()
                    for (i in 0 until jsonArray.length()) {
                        val jsonObject = jsonArray.getJSONObject(i).toString()
                        mlist.add(gson.fromJson(jsonObject, rows))
                    }
                    println(mlist)
                    return mlist
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            } catch (e: Exception) {
                Log.e("HTTPERROR", "Gl->>>数据解析异常" + e.message)
            }
            return null
        }
    }

    init {
        //创建拦截对象
        logInterceptor = HttpLoggingInterceptor()
        if (Config.IS_DEBUG) {
            // 这句一定要写,否则没有数据输出
            logInterceptor!!.level = HttpLoggingInterceptor.Level.BODY
        } else {
            logInterceptor!!.level = HttpLoggingInterceptor.Level.NONE
        }
        //自定义OkHttp
        val okHttpClient = OkHttpClient.Builder()
            .connectTimeout(10000L, TimeUnit.MILLISECONDS)
            .readTimeout(10000L, TimeUnit.MILLISECONDS)
            .addInterceptor(logInterceptor)
            .build()
        okHttp = MyOkHttp(okHttpClient)
    }

}